// Testcppflib_2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "cppflibinc.h"


#if defined(linux)
#include <string.h>
#endif

using namespace cppflib;
using namespace cppflib::threading;

static const int NAMEDSEMLOOPCOUNT = 10;

static void PostNamedSemaphore(void)
{
   cppmempool::MemPoolWrap localPool;

   // these semaphores are already created in another process
   Semaphore *pSem = new Semaphore(_S("hello_world"), 1);
   Semaphore *pSem2 = new Semaphore(_S("hello_world2"), 1);
   Semaphore *pEndSem = new Semaphore(_S("endloop"), 1);

   assert(!pSem->IsFirstInstance());
   assert(!pEndSem->IsFirstInstance());

   printf("Testcppflib_2: Notifying named semaphore in another process...\n");

   for (int i = 0; i < NAMEDSEMLOOPCOUNT; ++i) {
      if (i == NAMEDSEMLOOPCOUNT - 1) // ending condition must be put here
         pEndSem->Post();

      pSem->Post();
      pSem2->Wait();
   }

}

static void DummyPrint(void)
{
   printf("\n");
   for (int i =0; i < 10; ++i)
      printf("Testcppflib_2: I am running (%d) ...\n", i);
}


#if defined(WIN32)
int _tmain(int argc, _TCHAR* argv[])
#elif defined(linux)
int main(int argc, char * argv[])
#endif
{
    cppmempool::GlobalInit();

    if (argc >= 2) {

#if defined(WIN32)
       if (CFString::WStrcmp(argv[1], _S("-tnamedsem")) == 0)
          PostNamedSemaphore();
#elif defined(linux)
       if (strcmp(argv[1], "-tnamedsem") == 0)
          PostNamedSemaphore();
#endif

    }
    else {
       DummyPrint();
    }

    Thread::Sleep(1000);

    cppmempool::GlobalFinish();
    
	return 123;
}

